<template>
  <div class="header-container">
    <div class="logo">
      <h2>TodoList</h2>
    </div>
    <div class="user-info" @click="toggleDropdown">
      <el-avatar :size="40" :src="avatarUrl" />
      <div class="username">{{ username }}</div>
      <div class="user-dropdown" v-show="showDropdown">
        <div class="user-profile">
          <div class="profile-header">
            <el-avatar :size="40" :src="avatarUrl" />
            <div class="profile-info">
              <div class="profile-name">{{ username }}</div>
              <div class="profile-email" v-if="userStore.user?.email">{{ userStore.user.email }}</div>
            </div>
          </div>
        </div>
        <div class="dropdown-item" @click="logout">退出登录</div>
      </div>
    </div>
  </div>
</template>

<script setup lang="ts">
import { ref, onMounted, computed } from 'vue'
import { useRouter } from 'vue-router'
import { useUserStore } from '@/store/user'

const router = useRouter()
const userStore = useUserStore()

const avatarUrl = ref('https://cube.elemecdn.com/0/88/03b0d39583f48206768a7534e55bcpng.png')
const showDropdown = ref(false)

const username = computed(() => {
  return userStore.user?.username || '未知用户'
})

onMounted(() => {
  // 从store获取用户信息
  if (userStore.user?.avatar) {
    avatarUrl.value = userStore.user.avatar
  }
})

const toggleDropdown = () => {
  showDropdown.value = !showDropdown.value
}

const logout = async () => {
  try {
    await userStore.logout()
    router.push('/login')
  } catch (error) {
    console.error('退出登录失败:', error)
  }
}
</script>

<style scoped>
.header-container {
  display: flex;
  justify-content: space-between;
  align-items: center;
  width: 100%;
  height: 100%;
  padding: 0 20px;
  position: relative;
  box-sizing: border-box;
}

.logo {
  display: flex;
  align-items: center;
}

.logo h2 {
  margin: 0;
  color: #67c23a;
  font-size: 24px;
}

.user-info {
  display: flex;
  align-items: center;
  cursor: pointer;
  position: relative;
}

.username {
  margin-left: 10px;
  font-size: 16px;
  color: #5d6d74;
  font-weight: 500;
}

.user-dropdown {
  position: absolute;
  top: 100%;
  right: 0;
  background: white;
  border-radius: 8px;
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
  min-width: 250px;
  z-index: 100;
}

.user-profile {
  padding: 20px;
  border-bottom: 1px solid #eee;
}

.profile-header {
  display: flex;
  align-items: center;
}

.profile-info {
  margin-left: 12px;
  flex: 1;
}

.profile-name {
  font-weight: 600;
  font-size: 16px;
  color: #333;
  margin-bottom: 4px;
}

.profile-email {
  font-size: 14px;
  color: #999;
}

.dropdown-item {
  padding: 12px 20px;
  color: #606266;
  cursor: pointer;
  font-size: 14px;
}

.dropdown-item:hover {
  background-color: #f5f7fa;
  color: #409eff;
}
</style>
